<template>
    <template v-if="!enableUpload">
        <el-image  :src="data?.path" fit="contain"></el-image>
    </template>
    <template v-else>
        <el-upload class="upload" action="" :on-change="handleUploadChange" :auto-upload="false" v-loading="uploadLoading" :show-file-list="false">
            <el-image class="el-upload-result" v-if="imageUrl" :src="imageUrl" fit="cover"></el-image>
            <i v-else class="el-icon-plus uploader-icon"></i>
        </el-upload>
    </template>

</template>

<script lang="ts">
import { IAssetsModel } from '@/headers/admin/model.h'
import { useAdminStore } from '@/store/admin';
import { UploadAssetsAction } from '@/store/admin/actions/assets';
import { useLoadingStatus } from '@/utils';
import { ElFile } from 'element-plus/lib/el-upload/src/upload.type';
import {defineComponent, PropType, ref, watch} from 'vue'
export interface IAssetDisplayProps {
    data?:IAssetsModel
    enableUpload:boolean
}
export default defineComponent({
    props:{
        data:{
            type:Object as PropType<IAssetsModel>,
            required:false
        },
        enableUpload:{
            type:Boolean,
            default:false
        }
    },
    emits:["update:data"],
    setup(props:IAssetDisplayProps,ctx) {
        const imageUrl = ref(props.data?.path??"");
        const propsRef = ref(props);
        function handleUploadSuccess(_res:any,file:File) {
            imageUrl.value = URL.createObjectURL(file)
        }
        const store = useAdminStore();
        const {loadingFunc:handleUploadChange,loading:uploadLoading}= useLoadingStatus(async function (file:{raw:File}[],filelist:ElFile[]) {
            const res = await UploadAssetsAction.getInstance().call(store,{file:file[0].raw});
            ctx.emit("update:data",res);
            handleUploadSuccess(res,file[0].raw);
        })
        watch(propsRef,(p)=>{
          console.log('data',p.data);
          if(p.data?.path){
            imageUrl.value = p.data.path;
          }
        },{deep:true})
        return {
            imageUrl,
            handleUploadSuccess,
            handleUploadChange,
            uploadLoading
        }
    },
})
</script>
<style lang="scss" scoped>

.uploader-icon {
    width:178px;
    height:178px;
    line-height: 178px;
    font-size:28px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
}
.el-upload-result {
  width:178px;
  height:178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}
</style>
